package PrjHttpTest

import (
	"bytes"
	"crypto/tls"
	"dgo/goutils/utils"
	"encoding/base64"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"time"
)

var DefHttpClient = http.Client{Transport: &http.Transport{
	TLSClientConfig:       &tls.Config{InsecureSkipVerify: true}, //跳过证书的有效认证
	MaxIdleConns:          100,
	MaxIdleConnsPerHost:   2,
	IdleConnTimeout:       90 * time.Second,
	TLSHandshakeTimeout:   10 * time.Second,
	ExpectContinueTimeout: 1 * time.Second,
	DialContext: (&net.Dialer{
		Timeout:   30 * time.Second,
		KeepAlive: 30 * time.Second,
	}).DialContext,
},
	Timeout: time.Minute * 5, //设置超时时间，5分钟
}

type SpcjinspOpera struct {
	user           string
	pass           string
	cookie         string
	verifyCode     string
	form_lt        string
	form_execution string
	form_eventId   string
	loginflag      int
}

func Base64Encode(data []byte) string {
	strBase := base64.StdEncoding.EncodeToString(data)
	return strBase
}

func NewSpcjinspOpera(user, pass, cookie string) *SpcjinspOpera {
	rval := &SpcjinspOpera{
		user:      user,
		pass:      pass,
		cookie:    cookie,
		loginflag: 1,
	}
	return rval
}

func (this *SpcjinspOpera) getVerifyCode() (error, string) {
	lvurl := "https://spcj.gsxt.gov.cn/code"
	req, err := http.NewRequest("GET", lvurl, nil)
	if err != nil {
		return err, ""
	}
	req.Header.Set("Host", "spcj.gsxt.gov.cn")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
	req.Header.Set("X-Requested-With", "XMLHttpRequest")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
	req.Header.Set("Referer", "https://spcj.gsxt.gov.cn/login")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	if len(this.cookie) > 0 {
		req.Header.Set("Cookie", "JSESSIONID="+this.cookie)
	}
	resp, err := DefHttpClient.Do(req)
	if err != nil {
		return err, ""
	}

	defer resp.Body.Close()
	rawstr := resp.Header.Get("Set-Cookie")
	strs := strings.Split(rawstr, ";")
	strcode := rawstr
	if len(strs) > 0 {
		strcode = strs[0]
	}

	if strings.HasPrefix(strcode, "code=") {
		return nil, strings.TrimPrefix(strcode, "code=")
	}
	return nil, ""
}

func (this *SpcjinspOpera) checkBeforeLogin() error {

	//lvBodyStr := "username=MTM3NzA0NDgxODM%3D&password=TmNieiQ3NDExOTgx&validate=p2w8&certKey=&lt=LT-451609-34X2jHtXrSbesghBCVWGdgsew21aFL&execution=e2s1&_eventId=submit&UserPwd=&UserSignedData=&UserCert=&ContainerName=&strRandom="

	lvBodyStr := fmt.Sprintf("username=%s%s&password=%s&validate=%s&certKey=",
		Base64Encode([]byte(this.user)), "%3D", Base64Encode([]byte(this.pass)), this.verifyCode)

	// 13770448183
	lvurl := fmt.Sprintf("https://spcj.gsxt.gov.cn/service/systemLoginRecord/addAndUpdateRecord?userName=%s", this.user)
	req, err := http.NewRequest("GET", lvurl, bytes.NewReader([]byte(lvBodyStr)))
	if err != nil {
		return err
	}
	req.Header.Set("Host", "spcj.gsxt.gov.cn")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
	req.Header.Set("X-Requested-With", "XMLHttpRequest")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
	req.Header.Set("Sec-Fetch-Site", "same-origin")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Referer", "https://spcj.gsxt.gov.cn/login")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	cookeraw := fmt.Sprintf("JSESSIONID=%s;  accountInfo=%s%s%s", this.cookie, this.user, "%26", Base64Encode([]byte(this.pass)))
	req.Header.Set("Cookie", cookeraw)
	resp, err := DefHttpClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	if resp.StatusCode == 200 {
		return nil
	}
	return fmt.Errorf("[%d]", resp.StatusCode)
}

func (this *SpcjinspOpera) checkTransTest2() error {
	lvurl := "https://spcj.gsxt.gov.cn/login?service=https://spcjinsp.gsxt.gov.cn/test_platform/?token="
	req, err := http.NewRequest("GET", lvurl, nil)
	if err != nil {
		return err
	}
	req.Header.Set("Host", "spcj.gsxt.gov.cn")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Upgrade-Insecure-Requests", "1")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0")
	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
	cookeraw := fmt.Sprintf("JSESSIONID=%s; code=%s", this.cookie, this.verifyCode)
	req.Header.Set("Cookie", cookeraw)
	resp, err := DefHttpClient.Do(req)
	fmt.Println(resp.Header)

	buf, _ := ioutil.ReadAll(resp.Body)
	strBody := string(buf)
	fmt.Println(strBody)
	return nil
}

func (this *SpcjinspOpera) checkTransTestCookie() error {
	lvurl := "https://spcjinsp.gsxt.gov.cn/test_platform/?token="
	req, err := http.NewRequest("GET", lvurl, nil)
	if err != nil {
		return err
	}
	req.Header.Set("Host", "spcjinsp.gsxt.gov.cn")
	req.Header.Set("Connection", "keep-alive")
	//req.Header.Set("sec-ch-ua",""Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"")
	//req.Header.Set("sec-ch-ua-mobile","?0")
	req.Header.Set("Upgrade-Insecure-Requests", "1")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36")
	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
	resp, err := DefHttpClient.Do(req)
	fmt.Println(resp.Header)

	buf, _ := ioutil.ReadAll(resp.Body)
	strBody := string(buf)
	fmt.Println(strBody)
	return nil
}

func (this *SpcjinspOpera) checkLogin() error {
	if len(this.cookie) == 0 {
		this.checkGetCookie()
	}
	if this.loginflag == 0 {
		return nil
	}
	err, verifyCode := this.getVerifyCode()
	if err != nil {
		return nil
	}

	this.verifyCode = verifyCode

	time.Sleep(time.Second * 5)

	this.checkBeforeLogin()

	//lvBodyStr := "username=MTM3NzA0NDgxODM%3D&password=TmNieiQ3NDExOTgx&validate=p2w8&certKey=&lt=LT-451609-34X2jHtXrSbesghBCVWGdgsew21aFL&execution=e2s1&_eventId=submit&UserPwd=&UserSignedData=&UserCert=&ContainerName=&strRandom="

	lvBodyStr := fmt.Sprintf("username=%s%s&password=%s&validate=%s&certKey=&lt=%s&execution=%s&_eventId=%s&UserPwd=&UserSignedData=&UserCert=&ContainerName=&strRandom=",
		Base64Encode([]byte(this.user)), "%3D", Base64Encode([]byte(this.pass)), this.verifyCode, this.form_lt, this.form_execution, this.form_eventId)
	lvurl := "https://spcj.gsxt.gov.cn/login"
	req, err := http.NewRequest("POST", lvurl, bytes.NewReader([]byte(lvBodyStr)))
	if err != nil {
		return err
	}
	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
	req.Header.Set("Sec-Fetch-Site", "same-origin")
	req.Header.Set("Sec-Fetch-Mode", "navigate")
	req.Header.Set("Sec-Fetch-Dest", "document")

	req.Header.Set("Referer", "https://spcj.gsxt.gov.cn/ui/index")
	req.Header.Set("Accept-Encoding", "deflate,br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
	cookeraw := fmt.Sprintf("JSESSIONID=%s; code=%s; accountInfo=%s%s%s", this.cookie, this.verifyCode, this.user, "%26", Base64Encode([]byte(this.pass)))
	req.Header.Set("Cookie", cookeraw)
	resp, err := DefHttpClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	//buf, _ := ioutil.ReadAll(resp.Body)
	//strBody := string(buf)
	//fmt.Println(strBody)
	//fmt.Println(re)
	if resp.StatusCode == 200 {
		return nil
	}

	return fmt.Errorf("[%d]", resp.StatusCode)
}

func (this *SpcjinspOpera) checkGetCookie() error {
	if len(this.cookie) == 0 {
		req, err := http.NewRequest("GET", "https://spcj.gsxt.gov.cn/login", nil)
		if err != nil {
			return err
		}

		req.Header.Set("Host", "spcj.gsxt.gov.cn")
		req.Header.Set("Connection", "keep-alive")
		req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
		req.Header.Set("X-Requested-With", "XMLHttpRequest")
		req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
		req.Header.Set("Sec-Fetch-Site", "same-origin")
		req.Header.Set("Sec-Fetch-Mode", "navigate")
		req.Header.Set("Sec-Fetch-Dest", "document")
		req.Header.Set("Referer", "https://spcj.gsxt.gov.cn/ui/index")
		req.Header.Set("Accept-Encoding", "deflate,br")
		req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
		resp, err := DefHttpClient.Do(req)
		if err != nil {
			return err
		}

		defer resp.Body.Close()
		rawstr := resp.Header.Get("Set-Cookie")
		strs := strings.Split(rawstr, ";")
		if len(strs) > 0 {
			this.cookie = strings.TrimPrefix(strs[0], "JSESSIONID=")
			if len(this.cookie) == 0 {
				return fmt.Errorf("未获取到JESSIONID值:%s", rawstr)
			}
			this.loginflag = 1
		}

		buf, _ := ioutil.ReadAll(resp.Body)
		strBody := string(buf)
		strform := utils.GetBetween(strBody, "<div class=\"form-group margin-top-1\">", "</div>", 0)
		if len(strform) == 0 {
			return fmt.Errorf("响应张找不到form数据, 请重新核实")
		}
		this.form_lt = utils.GetBetween(strform, "<input type=\"hidden\" name=\"lt\" value=\"", "\"/>", 0)
		this.form_execution = utils.GetBetween(strform, "<input type=\"hidden\" name=\"execution\" value=\"", "\"/>", 0)
		this.form_eventId = utils.GetBetween(strform, "<input type=\"hidden\" name=\"_eventId\" value=\"", "\"/>", 0)
		if len(this.form_lt) == 0 {
			return fmt.Errorf("响应数据找不到lt数据, 请重新核实")
		}
	}
	return nil
}

func (this *SpcjinspOpera) Qry(sessionid string) {
	lvUrl := "https://spcjinsp.gsxt.gov.cn/test_platform/api/food/getFood?order=desc&offset=0&limit=10&dataType=8&startDate=2020-02-22&endDate=2021-04-22&taskFrom=&samplingUnit=&testUnit=&enterprise=&sampledUnit=&foodName=&province=&reportNo=&bsfla=&bsflb=&sampleNo=&foodType1=&foodType4=&sampleNo_index=0&_=1619044942396"
	//clt := &http.Client{}
	req, _ := http.NewRequest("GET", lvUrl, nil)

	req.Header.Set("Host", "spcjinsp.gsxt.gov.cn")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
	req.Header.Set("X-Requested-With", "XMLHttpRequest")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
	req.Header.Set("Sec-Fetch-Site", "same-origin")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Referer", "https://spcjinsp.gsxt.gov.cn/test_platform/foodTest/search/0?v=4.0")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	cookeraw := fmt.Sprintf("JSESSIONID=%s", this.cookie)
	if len(sessionid) > 0 {
		cookeraw = fmt.Sprintf("JSESSIONID=%s", sessionid)
	}

	req.Header.Set("Cookie", cookeraw)
	response, err := DefHttpClient.Do(req)
	if err != nil {
		//fmt.Println(err)
		return
	}
	defer response.Body.Close()
	buf, _ := ioutil.ReadAll(response.Body)
	json := wrapper.NewSVObjectFromBufIfErrThenNew(buf)
	fmt.Println(json.AsJSONString(false))
}
